
import dayjs from 'dayjs';
//获取公共组件的国际化预研

/**
 * @function 获取url的参数
 */
export function getQueryString(name) {
    const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    const r = window.location.search.substr(1).match(reg);
    if (r !== null) return unescape(r[2]); return null;
}

/**
 * @function 获取本地语言
 */
export function getLocalLanguage() {
    const language = localStorage.getItem('language');
    const browserLanguage = (navigator.language || navigator.browserLanguage).substr(0, 2);
    return language ? language : browserLanguage.includes('zh') ? 'zh-cn' : browserLanguage;
}

/**
 * @function 获取时间
 * @desc 获取今日，昨日，本周，本月
 */
export function getSpecialDate() {
    //昨天的时间
    const today = dayjs().format("YYYY-MM-DD");
    const yesterday = dayjs().subtract(1, 'day').format("YYYY-MM-DD");
    const weekStartDate = dayjs().startOf('week').format("YYYY-MM-DD");
    const weekEndDate = dayjs().endOf('week').format("YYYY-MM-DD");
    const monthStartDate = dayjs().startOf('month').format("YYYY-MM-DD");
    const monthEndDate = dayjs().endOf('month').format("YYYY-MM-DD");
    return {
        today,
        yesterday,
        weekDate: [weekStartDate, weekEndDate],
        monthDate: [monthStartDate, monthEndDate],
    }
}

/**
 * @function 处理图片或文件链接
 */
export function handleImageOrFile(url) {
    if (!url) return '';
    if (url.includes('http://') || url.includes('https://')) {
        return url.includes('token') ? url : url + '?token=' + localStorage.accessToken
    } else if (url.includes('data:image') || url.includes('/evo-oss/')) {
        return url
    } else if (url) {
        const returnUrl = window.location.origin + '/evo-apigw/evo-oss/' + url + '?token=' + localStorage.accessToken
        return returnUrl
    }
    return ''
}

/**
 * @function 时间格式化
 * @param {*} date 时间
 * @param {String} format 格式化
 */
export function dateFormat(date, format = 'YYYY-MM-DD') {
    return dayjs(date).format(format)
}

/**
 * @function 获取页面前缀
 */
export function getBasePath() {
    let basePath = ''
    if (!window.location.origin) {
        basePath = window.location.protocol + '//' + window.location.host + '/'
    } else {
        basePath = window.location.origin + '/'
    }
    return basePath
}

/**
  * @method HTMLDecode 反转义特殊字符
  * @param {String} text 字符串
  * @returns {String}
  */
export function HTMLDecode(text, type) {
    if (type === 'match') {
        const SPECIAL_CHARS = ["%", "_", "<", ">", "(", ")", '"', "&", " "]
        const ESCAPE_SPECIAL_CHARS = ["\\%", "\\_", "&lt;", "&gt;", "&#40;", "&#41;", "&quot;", "&amp;", "&nbsp;"]
        ESCAPE_SPECIAL_CHARS.forEach((item, i) => {
            text = text.replace(new RegExp(item, 'gm'), SPECIAL_CHARS[i])
        })
        return text
    }
    let temp = document.createElement("div")
    temp.innerHTML = text
    const output = temp.innerText || temp.textContent
    temp = null
    return output
}

/**
 * @method decodeObj() 转化html中的转义字符
 * @param obj 获取的对象
 * @returns {Object}
 */
export function decodeObj(obj) {
    if (typeof obj === 'string') {
        return HTMLDecode(obj, 'match')
    } else if (typeof obj === 'object' && !(obj instanceof Array) && obj !== null) {
        //object
        const temp = {}
        for (const [key, value] of Object.entries(obj)) {
            temp[key] = decodeObj(value)
        }
        return temp
    } else if (typeof obj === 'object' && obj instanceof Array) {
        // array
        return obj.map(item => {
            return decodeObj(item)
        })
    }
    return obj
}

/**
 * @method localSClear() 清除localstorage，保留指定的项
 * @param {Array} arr 需要保留在localstorage中的key集合
 */
export function localSClear(arr = ['UserName', 'language', 'checked', 'rememberToken']) {
    const delKey = []
    for (let i = 0; i < localStorage.length; i++) {
        const key = localStorage.key(i) || ''
        if (!arr.includes(key) && !key.includes('oms_')) {
            delKey.push(key)
        }
    }
    delKey.forEach(val => {
        localStorage.removeItem(val)
    })
}

/**
 * @function 多维数组指定子项扁平化函数
 * @param array              要执行的扁平化数组
 * @param childrenKeys       要参与扁平的子键名数组 默认 ['children']
 * @param flattenParent      默认的父数组
 * @param flattenParentKey   被压平后子项父数组存放键名
 * @returns Array
 */
export function arrayChildrenFlatten(array, { childrenKeys, flattenParent, flattenParentKey } = { childrenKeys: ["children"], flattenParent: [], flattenParentKey: "flattenParent" }) {
    const result = [];
    array.forEach(item => {
        const flattenItem = JSON.parse(JSON.stringify(item));
        flattenItem[flattenParentKey] = flattenParent;
        result.push(flattenItem);
        childrenKeys.forEach(key => {
            if (item[key] && Array.isArray(item[key])) {
                const children = arrayChildrenFlatten(item[key], {
                    childrenKeys,
                    flattenParent: [...flattenParent, item],
                    flattenParentKey
                });
                result.push(...children);
            }
        });
    });
    return result;
}

/**
 * @function 直接下载文件
 */
export async function createIframeDownload(url, params) {
    let realUrl = await  urlRecast(url)
    const paramsGet = Object.keys(params || {}).map(k => `${k}=${params[k] || ''}`)
    paramsGet.length && (realUrl += `?${paramsGet.join('&')}`)
    let ifr = document.getElementById('downloadIframe')
    if (!ifr) {
        // document.body.removeChild(ifr);
        ifr = document.createElement('iframe')
        ifr.id = 'downloadIframe'
        ifr.style.display = 'none'
        document.body.appendChild(ifr)
    }
    ifr.src = realUrl
}

/**
* 深度克隆对象，不支持对象内方法的克隆
* @param {Objectany} source 待拷贝对象
* @returns {Object}
*/
export function deepClone(source) {
    return JSON.parse(JSON.stringify(source))
}

/**
 * @function 处理接口返回的图片
 */
export function pictureTrans(path) {
    let userHost = '';
    if (process.env.NODE_ENV === "development") {
        userHost = "https://10.38.106.200/"
    } else {
        const top = window.top || { location: { port: '', protocol: '', hostname: {} } };
        const location = top.location;
        const protocol = location.protocol;
        const ip = location.hostname;
        const port = location.port;
        userHost = protocol + '//' + ip + ':' + port + '/';
    }
    const result = `${userHost}evo-apigw/evo-oss/${path}?token=${localStorage.getItem('accessToken')}`
    return result || '';
}

// 动态获取图片路径
export function getImageUrl(picPath) {
    const subSystem = import.meta.env.VITE_SYSTEMPATH;
    // return new URL(, import.meta.url).href;
    return `/${subSystem}/${picPath}`
}